package com.hzy.fivepalace.db.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzy.fivepalace.common.exception.TransactionalException;
import com.hzy.fivepalace.common.util.DateUtils;
import com.hzy.fivepalace.common.util.OrderUtils;
import com.hzy.fivepalace.db.dao.DtsGroupOpenDetailMapper;
import com.hzy.fivepalace.db.dao.DtsGroupOpenListMapper;
import com.hzy.fivepalace.db.dao.DtsOrderMapper;
import com.hzy.fivepalace.db.domain.*;
import com.hzy.fivepalace.db.service.DtsGroupOpenListService;
import com.hzy.fivepalace.db.service.RefundService;
import com.hzy.fivepalace.db.service.base.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 拼团成团 列Service业务层处理
 *
 * @author ruoyi
 * @date 2022-11-07
 */
@Service
public class DtsGroupOpenListServiceImpl extends BaseServiceImpl<DtsGroupOpenListMapper, DtsGroupOpenList> implements DtsGroupOpenListService {

    @Resource
    private DtsGroupOpenListMapper groupOpenListMapper;
    @Resource
    private DtsGroupOpenDetailMapper groupOpenDetailMapper;
    @Resource
    private DtsOrderMapper productOrderMapper;

    @Resource
    private RefundService refundService;

    @Value("${hzy.wx.refund-notify-url}")
    private String refund_notify_url;//微信支付的回调地址

    @Value("${hzy.wx.app-id}")
    private String appid;
    @Value("${hzy.wx.app-secret}")
    private String secret;
//    @Value("${hzy.wx.mch_id}")
//    private String mch_id;
//    @Value("${hzy.wx.api_key}")
//    private String api_key;
//    @Value("${hzy.wx.keyPath}")
//    private String keyPath;//微信支付的回调地址


    @Override
    @Transactional
    public DtsGroupOpenList addGroupOpen(DtsUser user, DtsGroupProduct groupProduct, DtsOrder order, int isOwner) {
        DtsGroupOpenList groupOpenList = new DtsGroupOpenList();
        int ret = 0;
        try{
            Date nowTime = new Date();
            groupOpenList.setGroupId(groupProduct.getId());
            groupOpenList.setUserCount(groupProduct.getUserCount());
            groupOpenList.setCreateTime(nowTime);
            String groupNo = OrderUtils.generateOrderNo();
            groupOpenList.setGroupNo(groupNo);
            groupOpenList.setOwnerOrderId(order.getId());
            groupOpenList.setBeginTime(nowTime);
            // 未成团的 过期时间  12小时有效期
            groupOpenList.setEndTime(DateUtils.getAfterSecondsByOld(nowTime, 12 * 60 * 60));
            groupOpenList.setState(0);
            groupOpenList.setOwnerId(user.getId());
            groupOpenList.setBuyUserCount(0);
            groupOpenList.setWarnTime(new Date());
            ret = groupOpenListMapper.insert(groupOpenList);
            if(ret <= 0){

            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return groupOpenList;
    }

    @Override
    public DtsGroupOpenList getGroupByDtsOrderId(Integer orderId) {
        QueryWrapper<DtsGroupOpenList> qw = new QueryWrapper<>();
        qw.eq("owner_order_id", orderId);
        qw.last("limit 1");
        return groupOpenListMapper.selectOne(qw);
    }

    @Override
    public DtsGroupOpenList getGroupByGroupNo(String openNo) {
        QueryWrapper<DtsGroupOpenList> qw = new QueryWrapper<>();
        qw.eq("group_no", openNo);
        qw.last("limit 1");
        return groupOpenListMapper.selectOne(qw);
    }

    @Override
    @Transactional
    public int refundOpenList(DtsGroupOpenList openList) {
        int ret = 0;
        try{

            //状态  0 - 未达到人数  1 - 已经达到人数  2 - 团购已成功结束（已完成团购） 3 - 团购未达到人数 团购失败
            openList.setState(3);
            ret = groupOpenListMapper.updateById(openList);
            if(ret <=0){
                throw new TransactionalException("groupOpenListMapper updateById error");
            }

            int successCount = 0;
            QueryWrapper<DtsGroupOpenDetail> qw = new QueryWrapper<>();
            qw.eq("group_open_id",openList.getId());
            List<DtsGroupOpenDetail> details = groupOpenDetailMapper.selectList(qw);
            if(CollUtil.isNotEmpty(details)){
                for (DtsGroupOpenDetail openDetail : details){
                    DtsOrder order = productOrderMapper.selectByPrimaryKey(openDetail.getOrderId());
                    if(order != null){
                        Object result = refundService.initiateWechatRefund(order, "拼团未成功，系统自动退款",true);
                        JSONObject jsonObject = JSONUtil.parseObj(result);
                        if (jsonObject != null) {
                            int code = jsonObject.getInt("code");
                            if(code == 0){
                                successCount ++;
                            }
                            ret = code;
                        }
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("groupOpenListMapper updateById error");
        }
        return ret;
    }
}
